//
//  LHRedioTableViewController.m
//  EPA
//
//  Created by 卢浩 on 16/4/20.
//  Copyright © 2016年 卢浩. All rights reserved.
//

#import "LHRedioTableViewController.h"
#import "LHCycleScrollView.h"
#import "LHRadioImgModel.h"
#import "LHRadioModel.h"
#import "LHBaseModel.h"
#import "LHNetWorkRequestManager.h"
#import "LHBaseTableViewCell.h"
#import "LHRadioTableViewCell.h"
#import "LHRadioListController.h"
#import "LORefresh.h"
#import "LHRadioDownLoadController.h"

@interface LHRedioTableViewController ()

@property (nonatomic,strong) LHCycleScrollView *cycleView;

@property (nonatomic,strong) NSMutableArray *hotRedioData;

@property (nonatomic,strong) NSMutableArray *allRedioData;

@property (nonatomic,strong) NSMutableArray *imgArr;

@property (nonatomic,assign) NSInteger start;

@end

@implementation LHRedioTableViewController

- (void)dealloc{
    //自定义图片
    [self.tableView removeObserver:[self.tableView gifHeader] forKeyPath:@"contentOffset"];
    
    //底部
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentSize"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"电  台";
    
    self.hotRedioData = [NSMutableArray array];
    self.allRedioData = [NSMutableArray array];
    self.imgArr = [NSMutableArray array];
    
    [self loadData];
    
    //创建头轮播图
    self.cycleView = [[LHCycleScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width * 0.6) Interval:5];
    self.cycleView.defaultImg = [UIImage imageNamed:@"图片正在加载.jpeg"];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"LHRadioTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"LHRadioTableViewCell"];
    
    __weak typeof(self) weakSelf = self;
    //自定义图片
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderGif refreshingBlock:^{
        [weakSelf.allRedioData removeAllObjects];
        [weakSelf.hotRedioData removeAllObjects];
        [weakSelf.imgArr removeAllObjects];
        [weakSelf.tableView reloadData];
        weakSelf.start = 0;
        [weakSelf loadData];
    }];
    [[self.tableView gifHeader] setGifName:@"wangnima"];
    
    //添加上提加载更多
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        NSInteger count = weakSelf.allRedioData.count;
        [weakSelf loadDataWithStart:count];
    }];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"下载列表" style:(UIBarButtonItemStylePlain) target:self action:@selector(presentDownloadAction)];
}

//点击下载按钮
- (void)presentDownloadAction{
    LHRadioDownLoadController *radioDownloadVC = [[LHRadioDownLoadController alloc]init];
    UINavigationController *navc = [[UINavigationController alloc]initWithRootViewController:radioDownloadVC];
    [self presentViewController:navc animated:YES completion:nil];
}

//刷新按钮事件
- (void)reloadAction{
    [self.hotRedioData removeAllObjects];
    [self.allRedioData removeAllObjects];
    [self.imgArr removeAllObjects];
    [self.tableView reloadData];
    self.start = 0;
    [self loadData];
}

- (void)loadData{
    NSDictionary *paramsDict = @{@"auth":[LHUserInfoManager shareManager].auth,@"client":@(1),@"deviceid":@"63A94D37-33F9-40FF-9EBB-481182338873",@"radioid":@"55af6aab53479c66758b45b1",@"version":@"3.0.4"};
    [LHNetWorkRequestManager requestUrl:[NSURL URLWithString:RADIOLIST_URL] Methed:POST Params:paramsDict Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSDictionary *dataDict = dict[@"data"];
            
            NSArray *hotlistArr = dataDict[@"hotlist"];
            NSMutableArray *tempHotArr = [NSMutableArray array];
            for (NSDictionary *redioDict in hotlistArr) {
                LHRadioModel *model = [[LHRadioModel alloc]init];
                [model setValuesForKeysWithDictionary:redioDict];
                [tempHotArr addObject:model];
            }
            
            NSArray *alllistArr = dataDict[@"alllist"];
            NSMutableArray *tempAllArr = [NSMutableArray array];
            for (NSDictionary *redioDict in alllistArr) {
                LHRadioModel *model = [[LHRadioModel alloc]init];
                [model setValuesForKeysWithDictionary:redioDict];
                [tempAllArr addObject:model];
            }
            
            NSArray *carouselArr = dataDict[@"carousel"];
            NSMutableArray *imgArr = [NSMutableArray array];
            NSMutableArray *imgNameArr = [NSMutableArray array];
            for (NSDictionary *imgDict in carouselArr) {
                LHRadioImgModel *model = [[LHRadioImgModel alloc]init];
                [model setValuesForKeysWithDictionary:imgDict];
                [imgArr addObject:model];
                [imgNameArr addObject:model.img];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.hotRedioData addObjectsFromArray:tempHotArr];
                
                [self.allRedioData addObjectsFromArray:tempAllArr];
                
                [self.imgArr addObjectsFromArray:imgArr];
                
                [self.tableView reloadData];
                
                //自定义图片,收回下拉刷新
                [[self.tableView gifHeader] endRefreshing];
                
                if (imgNameArr.count != 0) {
                    self.cycleView.imgNameArray = imgNameArr;
                }else{
                    [self loadData];
                }
            });
        }
    }];
}

- (void)loadDataWithStart:(NSInteger)start{
    NSDictionary *paramsDict = @{@"auth":[LHUserInfoManager shareManager].auth,@"client":@(1),@"deviceid":@"6D4DD967-5EB2-40E2-A202-37E64F3BEA31",@"limit":@10,@"start":@(start),@"version":@"3.0.6"};
    [LHNetWorkRequestManager requestUrl:[NSURL URLWithString:RADIOMLISTORE_URL] Methed:POST Params:paramsDict Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSDictionary *dataDict = dict[@"data"];
            NSArray *alllistArr = dataDict[@"list"];
            NSMutableArray *tempAllArr = [NSMutableArray array];
            for (NSDictionary *redioDict in alllistArr) {
                LHRadioModel *model = [[LHRadioModel alloc]init];
                [model setValuesForKeysWithDictionary:redioDict];
                [tempAllArr addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.allRedioData addObjectsFromArray:tempAllArr];
                [self.tableView reloadData];
                //底部
                [[self.tableView defaultFooter] endRefreshing];
                if (tempAllArr.count == 0) {
                    [self loadDataWithStart:self.allRedioData.count];
                }
            });
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return self.hotRedioData.count;
    }else if(section == 2){
        return self.allRedioData.count;
    }else{
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 170;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return self.view.frame.size.width * 0.6 + 5;
    }else{
        return 30;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor lightGrayColor];
    UILabel *lable = [[UILabel alloc]init];
    if (section == 0) {
        [view addSubview:self.cycleView];
    }else if (section == 1){
        lable.text = @"最 热 电 台";
        lable.textAlignment = NSTextAlignmentCenter;
        lable.frame = CGRectMake(0, 0, self.view.frame.size.width, 30);
        [view addSubview:lable];
    }else if (section == 2){
        lable.text = @"全 部 电 台";
        lable.textAlignment = NSTextAlignmentCenter;
        lable.frame = CGRectMake(0, 0, self.view.frame.size.width, 30);
        [view addSubview:lable];
    }
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        LHBaseTableViewCell *cell = [LHBaseTableViewCell cellWithTableView:tableView Model:self.hotRedioData[indexPath.row] IndexPath:indexPath];
        return cell;
    }else if (indexPath.section == 2){
        LHBaseTableViewCell *cell = [LHBaseTableViewCell cellWithTableView:tableView Model:self.allRedioData[indexPath.row] IndexPath:indexPath];
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // 取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    LHRadioModel *model;
    if (indexPath.section == 1) {
        model = self.hotRedioData[indexPath.row];
    }else if (indexPath.section == 2){
        model = self.allRedioData[indexPath.row];
    }
    LHRadioListController *redioListVC = [[LHRadioListController alloc]init];
    redioListVC.radioid = model.radioid;
    redioListVC.titleStr = model.title;
    [self.navigationController pushViewController:redioListVC animated:YES];
}

@end
